//package nio.geek;
//
//import java.io.BufferedReader;
//import java.io.IOException;
//import java.io.InputStreamReader;
//import java.net.InetAddress;
//import java.net.InetSocketAddress;
//import java.net.Socket;
//import java.nio.ByteBuffer;
//import java.nio.channels.AsynchronousServerSocketChannel;
//import java.nio.channels.AsynchronousSocketChannel;
//import java.nio.channels.CompletionHandler;
//import java.nio.channels.SelectionKey;
//import java.nio.channels.Selector;
//import java.nio.channels.ServerSocketChannel;
//import java.nio.channels.SocketChannel;
//import java.nio.charset.Charset;
//import java.util.Iterator;
//import java.util.Set;
//
//public class AsynNIOServer extends Thread {
//    public static void main(String[] args) throws IOException {
//        AsynNIOServer server = new AsynNIOServer();
//        server.start();
//        // 实例化 = connect
//        Socket client = new Socket(InetAddress.getLocalHost(), 8889);
//        InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
//        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//        String bb = bufferedReader.readLine();
//        System.out.println("客户端:" + bb);
//    }
//
//    public void run() {
//        try {
//            // 创建Selector和Channel
//            AsynchronousServerSocketChannel serverSock = AsynchronousServerSocketChannel.open()
//                    .bind(new InetSocketAddress(InetAddress.getLocalHost(), 8889));
//
//            serverSock.accept(serverSock, new CompletionHandler<>() { //为异步操作指定CompletionHandler回调函数
//                @Override
//                public void completed(AsynchronousSocketChannel sockChannel, AsynchronousServerSocketChannel serverSock) {
//                    serverSock.accept(serverSock, this);
//                    // 另外一个 write（sock，CompletionHandler{}）
//                    sayHelloWorld(sockChannel, Charset.defaultCharset().encode("Hello World!"));
//                }
//            });
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    private void sayHelloWorld(ServerSocketChannel server, ByteBuffer d) throws IOException {
//        try (SocketChannel client = server.accept()) {
//            // 返回客户端
//            client.write(Charset.defaultCharset().encode("Hello world!"));
//        }
//    }
//}